package com.iwithlong.controller;

import com.imesne.assistant.common.runtime.RunBinder;
import com.iwithlong.context.ResultConst;
import com.iwithlong.service.WeixinService;
import com.iwithlong.utils.SignUtils;
import com.ktanx.platform.admin.controller.AdminBaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xiexiaohan on 2017/12/12.
 */
@Controller
@RequestMapping()
@Slf4j
public class WeixinController extends AdminBaseController {
    @Resource
    private WeixinService weixinService;

    @Value("${weixincustomtoken:null}")
    private String weixinCustomToken;

    @RequestMapping("m/weixin/accesstoken.json")
    public void accessToken(String grant_type,String appid,int offset,int count, Model model){
        Object jsonObject = weixinService.requestAccessToken(grant_type,appid,offset,count);
        if(RunBinder.hasErrors()){
            model.addAttribute(ResultConst.MESSAGE,RunBinder.getStrErrors());
            model.addAttribute(ResultConst.SUCCESS,false);
        }else {
            model.addAttribute(ResultConst.SUCCESS,true);
            model.addAttribute(ResultConst.RESULT,jsonObject);
        }
    }

    @RequestMapping("m/weixin/map.json")
    public void getMap(String appid,String js_code,String grant_type,Model model){
        Object jsonObject = weixinService.requestMapData(appid,js_code,grant_type);
        if(RunBinder.hasErrors()){
            model.addAttribute(ResultConst.MESSAGE,RunBinder.getStrErrors());
            model.addAttribute(ResultConst.SUCCESS,false);
        }else {
            model.addAttribute(ResultConst.SUCCESS,true);
            model.addAttribute(ResultConst.RESULT,jsonObject);
        }
    }

    @RequestMapping("m/weixin/requesturl")
    public String requestUrl(String url,Model model){
        String context = weixinService.requestWeixinPublic(url);
        if(RunBinder.hasErrors()){
            model.addAttribute("context",RunBinder.getStrErrors());
        }else {
            model.addAttribute("context",context);
        }
        return "weixin/weixin-request";
    }

    @RequestMapping("m/weixin/requesturl.json")
    public void requestUrlJson(String url,Model model){
        Object result = weixinService.requestWeixinJsonObject(url);
        if(RunBinder.hasErrors()){
            model.addAttribute(ResultConst.MESSAGE,RunBinder.getStrErrors());
            model.addAttribute(ResultConst.SUCCESS,false);
        }else {
            model.addAttribute(ResultConst.SUCCESS,true);
            model.addAttribute(ResultConst.RESULT,result);
        }
    }

    @RequestMapping("m/weixin/request/url")
    public String requestUrlTest(){
        return "weixin/article";
    }

//    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/m/weixinapp/interface.json")
    public void weixinAppService(HttpServletRequest request, HttpServletResponse response){
        //微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp，nonce参数
        String signature = request.getParameter("signature");
        //时间戳
        String timestamp = request.getParameter("timestamp");
        //随机数
        String nonce = request.getParameter("nonce");
        //随机字符串
        String echostr = request.getParameter("echostr");
        if (SignUtils.checkSignature(signature, timestamp, nonce,weixinCustomToken)) {
            log.info("[signature: "+signature + "]<-->[timestamp: "+ timestamp+"]<-->[nonce: "+nonce+"]<-->[echostr: "+echostr+"]");
            if(StringUtils.isNotBlank(echostr)){
                try {
                    response.getOutputStream().println(echostr);
                } catch (IOException e) {
                    log.info("写回失败");
                }
            }else {
                log.info("开始流程");
                weixinService.dealWithAppRequest(request,response);
            }
        }
    }


}
